package com.mp.approvalreq.util;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.entity.TemplateComponent;
import com.mp.approvalreq.entity.adjust.MoneyAmountNum;
import com.mp.approvalreq.entity.adjust.MultiChosen;
import com.mp.approvalreq.entity.adjust.PriorityShow;
import com.mp.approvalreq.entity.po.ComponentGroup;
import com.plusmoney.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 兼容工具类,用于处理各种兼容逻辑
 */
public class AdjustUtils {

    private static final Logger logger = LoggerFactory.getLogger(AdjustUtils.class);

    public static void adjustTemplate(Template template) {
        try {
            List<TemplateComponent> templateComponents = JSONObject.parseArray(template.getTemplateComponent(), TemplateComponent.class);
            Map<Integer, TemplateComponent> componentMap = ComponentUtils.getComponentMap(templateComponents);
            // 兼容列表展示项设置
            adjustPriorityShow(template, componentMap);
            // 兼容汇总求和公式
            adjustSummaryFormula(template, componentMap);
            // 兼容组件集id绑定
            adjustGroupId(template, componentMap);
            // 兼容单/多选项绑定
            adjustMultiChosen(template, componentMap);

            template.setTemplateComponent(JSONObject.toJSONString(templateComponents));
        } catch (Exception e) {
            logger.info("出错数据:{}", JSONObject.toJSONString(template));
            logger.error(e.getMessage(), e);
        }
    }

    private static void adjustMultiChosen(Template template, Map<Integer, TemplateComponent> componentMap) {
        if (StringUtils.isNotBlank(template.getMultiChosen())) {
            List<MultiChosen> multiChosenList = JSONObject.parseArray(template.getMultiChosen(), MultiChosen.class);
            for (MultiChosen multiChosen : multiChosenList) {
                if (!componentMap.containsKey(multiChosen.getNum())) {
                    continue;
                }
                TemplateComponent templateComponent = componentMap.get(multiChosen.getNum());
                templateComponent.setMultiChosen(multiChosen.getContent());
            }
        }
    }

    private static void adjustGroupId(Template template, Map<Integer, TemplateComponent> componentMap) {
        if (StringUtils.isNotBlank(template.getComponentGroupJson())) {
            List<ComponentGroup> componentGroups = JSONObject.parseArray(template.getComponentGroupJson(), ComponentGroup.class);
            for (ComponentGroup componentGroup : componentGroups) {
                if (!componentMap.containsKey(componentGroup.getNum())) {
                    continue;
                }
                TemplateComponent templateComponent = componentMap.get(componentGroup.getNum());
                templateComponent.setGroupId(componentGroup.getId());
            }
        }
    }

    private static void adjustSummaryFormula(Template template, Map<Integer, TemplateComponent> componentMap) {
        if (StringUtils.isNotBlank(template.getMoneyAmountNums())) {
            List<MoneyAmountNum> moneyAmountNums;
            try {
                moneyAmountNums = JSONObject.parseArray(template.getMoneyAmountNums(), MoneyAmountNum.class);
            } catch (Exception e) {
                logger.info("汇总公式解析出错:{}", JSONObject.toJSONString(template));
                return;
            }
            for (MoneyAmountNum moneyAmountNum : moneyAmountNums) {
                TemplateComponent templateComponent = componentMap.get(moneyAmountNum.getNum());
                if (Utils.isNull(templateComponent)) {
                    continue;
                }
                StringBuilder formula = new StringBuilder("f(x)=");
                try {
                    if (StringUtils.isNotBlank(moneyAmountNum.getNums())) {
                        List<Integer> list = Utils.string2list(moneyAmountNum.getNums());
                        for (Integer num : list) {
                            if (Objects.equals(num, templateComponent.getNum())) {
                                EmailUtils.sendMail("数据异常", template);
                                continue;
                            }
                            formula.append("num[").append(num).append("]");
                            formula.append("+");
                        }
                    }
                } catch (Exception e) {
                    logger.info("nums解析出错:{}====={}", JSONObject.toJSONString(template), JSONObject.toJSONString(moneyAmountNum));
                }
                List<MoneyAmountNum> groups = moneyAmountNum.getGroup();
                if (Utils.isNotEmpty(groups)) {
                    try {
                        for (MoneyAmountNum group : groups) {
                            if (StringUtils.isBlank(group.getNums())) {
                                continue;
                            }
                            if (Objects.equals(group.getNum(), templateComponent.getNum())) {
                                EmailUtils.sendMail("数据异常", template);
                                continue;
                            }
                            List<Integer> nums = Utils.string2list(group.getNums());
                            for (Integer num : nums) {
                                formula.append("group[").append(group.getNum()).append(",").append(num).append("]");
                                formula.append("+");
                            }
                        }
                    } catch (Exception e) {
                        logger.info("nums解析出错:{}====={}", JSONObject.toJSONString(template), JSONObject.toJSONString(moneyAmountNum));
                    }
                }
                try {
                    formula.deleteCharAt(formula.lastIndexOf("+"));
                    templateComponent.setSummaryFormula(formula.toString());
                } catch (Exception e) {
                    logger.info("公式为空:{}", JSONObject.toJSONString(template));
                }
            }
        }
    }

    private static void adjustPriorityShow(Template template, Map<Integer, TemplateComponent> componentMap) {
        PriorityShow priorityShow = PriorityShow.parsePriorityShow(template.getPriorityShow());
        if (Utils.isNotNull(priorityShow)) {
            if (Utils.isNotNull(priorityShow.getDescribeNum())) {
                TemplateComponent templateComponent = componentMap.get(priorityShow.getDescribeNum());
                if (Utils.isNotNull(templateComponent)) {
                    templateComponent.setShowType(TemplateComponent.SHOW_TYPE_DESCRIBE);
                }
            }
            if (Utils.isNotNull(priorityShow.getTimeNum())) {
                TemplateComponent templateComponent = componentMap.get(priorityShow.getTimeNum());
                if (Utils.isNotNull(templateComponent)) {
                    templateComponent.setShowType(TemplateComponent.SHOW_TYPE_TIME);
                }
            }
            if (Utils.isNotNull(priorityShow.getSummaryNum())) {
                TemplateComponent templateComponent = componentMap.get(priorityShow.getSummaryNum());
                if (Utils.isNotNull(templateComponent)) {
                    templateComponent.setShowType(TemplateComponent.SHOW_TYPE_COST);
                }
            }
        }
    }
}
